<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <el-form size="small" label-width="70px">
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="日期 ">
                <div class="flex flex-row">
                  <el-date-picker
                    v-model="query.startDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    value-format="yyyy-MM-dd"
                    placeholder="开始日期"
                    style="width: 100%;"
                  />
                  <el-date-picker
                    v-model="query.endDate"
                    align="right"
                    unlink-panels
                    class="fl1"
                    value-format="yyyy-MM-dd"
                    placeholder="结束日期"
                    style="width: 100%;"
                    :disabled="!query.startDate"
                    :pickerOptions="pickerOptions"
                  />
                </div>
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="单据编码">
                <el-input v-model="query.code" placeholder="输入编码进行搜索" />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="总店">
                <table-select
                  :tableColumns="[{prop:'code',label:'单位编码',width:'100'},{prop:'name',label:'往来单位名称',width: '280'}]"
                  :value.sync="query.pCustomerIds"
                  url="api/dropDown/basCustomerList"
                  :params="{customerAttr:1}"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售区域">
                <v-tree-select
                  v-model="customerAreaIds"
                  url="api/dropDown/basCustomerAreaTree"
                  multiple
                  value-consists-of="ALL_WITH_INDETERMINATE"
                  style="width: 100%"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户">
                <table-select
                  :tableColumns="[{prop:'code',label:'单位编码',width:'100'},{prop:'name',label:'往来单位名称',width: '280'}]"
                  :value.sync="query.customerIds"
                  placeholder="请选择往来单位"
                  url="api/dropDown/basCustomerList"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="客户分类">
                <v-tree-select
                  v-model="customerTypeIds"
                  url="api/dropDown/basCustomerTypeTree"
                  multiple
                  value-consists-of="ALL_WITH_INDETERMINATE"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="业务员">
                <zSelect
                  :value.sync="query.userIds"
                  url="api/dropDown/sysUserList"
                  style="width:  100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="销售部门">
                <v-tree-select
                  v-model="query.deptIds"
                  url="api/dropDown/sysDeptTree"
                  multiple
                  value-consists-of="ALL_WITH_INDETERMINATE"
                  style="width: 100%;"
                />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="打印状态">
                <v-select
                  v-model="query.isPrint"
                  :options="dict.common_yes_or_no"
                  placeholder="请选择打印状态"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="状态">
                <v-select
                  v-model="query.orderStatus"
                  :options="dict.common_order_status"
                  placeholder="请选择打印状态"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="备注">
                <el-input v-model="query.remark" />
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="10">
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <el-form-item label="二级代理">
                <zSelect
                  :value.sync="query.sCustomerIds"
                  url="api/dropDown/basCustomerList"
                  :params="{type:3}"
                  style="width:  100%;"
                />
              </el-form-item>
            </el-col>
            <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="6">
              <span>
              <el-button
                class="filter-item"
                size="mini"
                type="primary"
                @click="toQuery"
              >
                搜索
              </el-button>
              <el-button
                class="filter-item"
                plain
                size="mini"
                type="primary"
                @click="resetQuery"
              >
                重置
              </el-button></span>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <crudOperation :permission="permission">
        <el-button
          slot="left"
          v-permission="permission.add"
          class="filter-item"
          size="mini"
          type="primary"
          @click="toDetail"
        >
          新增
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.pass"
          class="filter-item"
          size="mini"
          type="success"
          :disabled="crud.selections.length < 1"
          @click="passOrReject('PASS')"
        >
          审核
        </el-button>
        <el-button
          slot="left"
          v-permission="permission.copy"
          class="filter-item"
          size="mini"
          type="warning"
          :disabled="crud.selections.length !== 1"
          @click="toCopy"
        >
          复制
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          @click="printIsSave"
        >
          打印
        </el-button>
        <el-button
          slot="right"
          class="filter-item"
          size="mini"
          type="warning"
          @click="crud.preView1"
        >
          打印预览
        </el-button>
      </crudOperation>
      <!--打印模板-->
      <el-dialog
        title="请选择打印模板"
        :visible.sync="crud.printConfig.pringDialog"
        width="30%"
      >
        <jPrintConfig
          groupId="orderMeeting"
          v-if="crud.printConfig.pringDialog"
          @getPrintId="crud.toPrint"
          :isPreview="crud.printConfig.isPreview"
        />
      </el-dialog>
      <!--打印预览-->
      <el-dialog
        title="打印预览"
        destroy-on-close
        v-dialogDrag
        close-on-press-escape
        :visible.sync="showPdf"
        append-to-body width="50vw"
      >
        <j-pdf :src="pdfSrc" />
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        stripe
        border
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        show-summary
        :summary-method="crud.sumRow"
        @selection-change="crud.selectionChangeHandler"
        @row-dblclick="toDetail"
        @contextmenu.native="showMenu"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column type="index" width="55" label="序号" />
        <el-table-column
          v-if="item.visible"
          v-for="(item, index) in crud.header"
          :key="`col_${index}`"
          :prop="item.prop"
          :label="columnLabel(item)"
          :width="item.width + 'px'"
          :data-porp='item.prop'
          @header-dragend="changeColWidth"
          :fixed="item.fixed"
          :sortable="item.sortable?'custom':false"
          :sort-orders="['descending', 'ascending', null]"
          sort-change="sort"
        >

          <template slot-scope="scope">
            <div v-if="item.type==1" :class="{'blue':(scope.row['orderStatus']==='INVALID')}">
              <div :class="{'red':(scope.row[`type`] === 2),'blue':(item.orderStatus==='INVALID')}">
                {{ scope.row[`${item.prop}`] }}
              </div>
            </div>
            <div v-else-if="item.type==2" :class="{'blue':(scope.row['orderStatus']==='INVALID')}">
              {{ scope.row[`${item.prop}`] | parseTime }}
            </div>
            <div v-else-if="item.type==3" :class="{'blue':(scope.row['orderStatus']==='INVALID')}">
              {{ getDict(`this.dict.label.${item.dictionary}["${scope.row[item.prop]}"]`) }}
            </div>
          </template>
        </el-table-column>

        <el-table-column
          v-permission="['admin','orderMeeting:edit','orderMeeting:del']"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
    <!--表格配置-->
    <el-dialog
      title="表格配置"
      :visible.sync="tableConfigShow"
      width="60%"
    >
      <j-table-column-config :columns.sync="crud.header" @tabSave="tabSave" @pit="pit" />
    </el-dialog>
    <!--contextmenu-->
    <vue-context-menu
      :contextMenuData="contextMenuData"
      @tableConfig="tableConfig"
      @deletedata="deletedata"
    />
  </div>
</template>

<script>
import crudOrderMeeting from '@/api/erp/orderMeeting'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import VSelect from '@/components/VSelect'
import VTreeSelect from '@/components/VTreeSelect'
import jPrintConfig from '@/components/jPrintConfig/jPrintConfig'
import jTableColumnConfig from '@/components/jTableColumnConfig/jTableColumnConfig'
import { tablemixins } from '@/mixins/tablemixins'

// crud交由presenter持有
const defaultCrud = CRUD({
  title: '订货会',
  url: 'api/orderMeeting',
  sort: 'id,desc',
  crudMethod: { ...crudOrderMeeting },
  optShow: {
    isShow: true,
    add: false,
    edit: false,
    del: true,
    download: true,
    leadingIn: true,
    enable: false,
    disable: false,
    pass: false,
    reject: false,
    copy: false,
    downloadDetail: true,
    recover: false,
    invalid: false,
    print: false, // 打印
    printDetail: false, // 打印详情
    unAccept: false, // 反验收
    accept: false // 验收
  },
  props: {
    searchToggle: true
  }
})
const defaultForm = {
  id: null,
  busdate: null,
  code: null,
  customerId: null,
  customerCode: null,
  customerName: null,
  customerAreaId: null,
  customerAreaCode: null,
  customerAreaName: null,
  customerTypeId: null,
  customerTypeCode: null,
  customerTypeName: null,
  userId: null,
  userCode: null,
  userName: null,
  deptId: null,
  deptCode: null,
  deptName: null,
  orderStatus: null,
  boxCount: null,
  count: null,
  taxAmount: null,
  noTaxAmount: null,
  tax: null,
  cancelStatus: null,
  unCancelAmount: null,
  cancelAmount: null,
  remark: null,
  contactName: null,
  contactPhone: null,
  sCustomerId: null,
  sCustomerCode: null,
  sCustomerName: null,
  isPrint: null,
  printCount: null,
  createUserId: null,
  createUserCode: null,
  createUserName: null,
  createTime: null,
  updateUserId: null,
  updateUserCode: null,
  updateUserName: null,
  updateTime: null,
  auditUserId: null,
  auditUserCode: null,
  auditUserName: null,
  auditTime: null,
  closeUserId: null,
  closeUserCode: null,
  closeUserName: null,
  closeTime: null,
  cancelUserId: null,
  cancelUserCode: null,
  cancelUserName: null,
  cancelDate: null
}
export default {
  name: 'OrderMeeting',
  components: {
    pagination,
    crudOperation,
    rrOperation,
    udOperation,
    VSelect,
    VTreeSelect,
    jPrintConfig,
    jTableColumnConfig
  },
  mixins: [presenter(defaultCrud), header(), form(defaultForm), crud(), tablemixins],
  dicts: ['common_yes_or_no', 'common_order_status', 't_sales_order_save_order_status_is_allow_print'],
  data() {
    return {
      permission: {
        add: ['admin', 'orderMeeting:add'],
        edit: ['admin', 'orderMeeting:edit'],
        del: ['admin', 'orderMeeting:del'],
        import: ['admin', 'orderMeeting:import'],
        export: ['admin', 'orderMeeting:export'],
        copy: ['admin', 'orderMeeting:copy'],
        upload: ['admin', 'orderMeeting:upload'],
        download: ['admin', 'orderMeeting:download'],
        pass: ['admin', 'orderMeeting:pass'],
        reject: ['admin', 'orderMeeting:reject'],
        closed: ['admin', 'orderMeeting:closed'],
        invalid: ['admin', 'orderMeeting:invalid'],
        stop: ['admin', 'orderMeeting:stop'],
        recover: ['admin', 'orderMeeting:recover']
      },
      rules: {
        customerId: [
          { required: true, message: '客户id不能为空', trigger: 'blur' }
        ]
      },
      customerTypeIds: [],
      customerAreaIds: []
    }
  },
  computed: {
    pickerOptions() {
      const startDate = this.query.startDate
      return {
        disabledDate(time) {
          return time.getTime() < new Date(startDate).getTime() - 3600 * 1000 * 24
        }
      }
    }
  },
  methods: {
    toQuery() {
      if (this.customerTypeIds) {
        this.query.customerTypeIds = this.customerTypeIds.join()
      }
      if (this.customerAreaIds) {
        this.query.customerAreaIds = this.customerAreaIds.join()
      }
      this.crud.page.page = 1
      this.crud.refresh()
    },
    resetQuery() {
      console.log(this.query.customerIds)
      if (this.query.customerTypeIds) {
        this.customerTypeIds = []
        this.query.customerTypeIds = ''
      }
      if (this.query.customerAreaIds) {
        this.customerAreaIds = []
        this.query.customerAreaIds = ''
      }
      this.crud.resetQuery()
    },
    toDetail(row) {
      const ids = row && row.id || 'add'
      const path = '/sale/orderMeetingDetail' + '/' + ids
      this.$router.push({ path: path })
    },
    toCopy() {
      const copyId = this.crud.selections.map(item => item.id)[0]
      this.$router.push({
        path: `/redirect/sale/orderMeetingDetail/copy=${new Date().getTime()}`,
        query: { copyId: copyId }
      })
    },
    passOrReject(type) {
      const data = {
        ids: this.crud.selections.map(item => item.id),
        type
      }
      this.crud.loadingOpen()
      crudOrderMeeting.passOrReject(data).then(() => {
        this.crud.loadingClose()
        this.$message.success('操作成功')
        this.crud.refresh()
      }).catch(() => {
        this.crud.loadingClose()
        this.$message.error('修改失败，稍后再试')
      })
    },
    printIsSave() {
      if (this.dict.t_sales_order_save_order_status_is_allow_print[0].value == '0') {
        if (this.crud.selections.some(item => item.orderStatus === 'SAVE')) return this.$message.error('保存状态单据不允许打印')
      }
      if (this.crud.selections.every(item => item.isPrint == '1')) {
        this.$confirm('订货单已打印，请确认是否重复打印', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.crud.preView()
          setTimeout(() => {
            this.crud.refresh()
          }, 6000)
        })
        return
      }

      this.crud.preView()
      setTimeout(() => {
        this.crud.refresh()
      }, 6000)
    }
  }
}
</script>

<style scoped>
.table-img {
  display: inline-block;
  text-align: center;
  background: #ccc;
  color: #fff;
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  vertical-align: middle;
  width: 32px;
  height: 32px;
  line-height: 32px;
}
</style>
